<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit" wrapClassName="modal-add">
    <BasicForm @register="registerForm">
    </BasicForm>
  </BasicModal>
</template>
<script lang="ts" setup>
import { ref, computed, unref, h, reactive, watch } from 'vue'
import { BasicModal, useModalInner } from '@/components/Modal'
import { BasicForm, useForm } from '@/components/Form'
import { addRecordFormSchema } from './data2'
import { addRecordPrice, modifyHistoryPrice } from '@/api/sys/energyUnitPrice'
import dayjs from 'dayjs'
import { message } from 'ant-design-vue'

defineOptions({ name: 'ModalAddRecord' })

const emit = defineEmits(['success', 'register'])

const isUpdate = ref(false)
const rowId = ref()

const [registerForm, { setFieldsValue, getFieldsValue, validateFields,
  updateSchema, resetFields, validate }] = useForm({
    labelWidth: 140,
    baseColProps: { span: 24 },
    schemas: addRecordFormSchema,
    showActionButtonGroup: false,
    actionColOptions: {
      span: 23,
    },
  })

const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
  resetFields();
  setModalProps({ confirmLoading: false })
  isUpdate.value = !!data?.isUpdate

  if (unref(isUpdate)) {
    rowId.value = data.record.id
    setFieldsValue({
      ...data.record,
      date: [data.record.startDate, data.record.endDate]
    })
  }
})

const getTitle = computed(() => (!unref(isUpdate) ? '新增单价' : '修改历史单价'))

async function handleSubmit() {
  try {
    const values = await validate()
    const { date, ...others } = values
    const params = {
      ...others,
      startDate: dayjs(date[0]).format('YYYY-MM-DD'),
      endDate: dayjs(date[1]).format('YYYY-MM-DD'),
    }
    params.name = '1'
    params.period = 'DEFAULT'
    console.log(params);

    setModalProps({ confirmLoading: true })
    // if (unref(isUpdate)) {
    params.id = rowId.value
    await modifyHistoryPrice(params)
    // } else {
    //   await addRecordPrice(params)
    // }
    message.success(isUpdate.value ? '修改成功' : '添加成功')
    closeModal()
    emit('success', { isUpdate: unref(isUpdate), values: { ...params, id: rowId.value } })
  } finally {
    setModalProps({ confirmLoading: false })
  }
}
</script>
<style lang="scss">
.modal-add {
  .ant-picker {
    width: 100%;
  }
}
</style>
